package qx.hyj.petrescue.Controller;


import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import qx.hyj.petrescue.VO.BlogVo;
import qx.hyj.petrescue.VO.CommentVo;
import qx.hyj.petrescue.VO.JsonResult;
import qx.hyj.petrescue.constens.ErrorCode;
import qx.hyj.petrescue.dto.BlogAdd;
import qx.hyj.petrescue.dto.BlogType;
import qx.hyj.petrescue.dto.CommentAdd;
import qx.hyj.petrescue.entity.Blog;
import qx.hyj.petrescue.entity.Comment;
import qx.hyj.petrescue.service.BlogService;


import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/Petrescue/blog")
public class BlogController {
    @Resource
    private BlogService blogService;

    @Autowired
    private ServletContext servletContext;

    @PostMapping("/Blogs")
    public JsonResult<JSONObject> Blogs(@RequestBody BlogType blogType){
        JSONObject loginResponse = new JSONObject();
        List<BlogVo> blogs = blogService.Blogs(blogType);
        if(blogs!=null){
            loginResponse.put("blogs",blogs);
            return new JsonResult<>(loginResponse);
        }else {
            return new JsonResult<>(null, ErrorCode.BLOG_AHOW_FAIL);
        }
    }

    @PostMapping("/addBlog")
    public JsonResult<Map> addBlog(@RequestParam("picture") MultipartFile picture, BlogAdd blogAdd, HttpServletRequest request){
        try {
            Integer userId = (Integer) request.getAttribute("id");
            // 生成唯一的文件名
            String originalFilename = picture.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString() + extension;
            // 指定存储路径
            // 将文件路径添加到结果中
            Blog blog = new Blog();

            blog.setTitle(blogAdd.getTitle());
            blog.setContent(blogAdd.getContent());
            blog.setDwtype(blogAdd.getDwType());
            blog.setBlogtype(blogAdd.getBlogType());
            blog.setAuthor(userId);
            String Way = "";
            switch (blog.getDwtype()) {
                case 1:
                    Way = "/static/images/dog/";
                break;
                case 2:
                   Way = "/static/images/cat/";
                break;
                case 3:
                   Way = "/static/images/other/";
                break;
            }
            String uploadDir = servletContext.getRealPath(Way);
            Path uploadPath = Paths.get(uploadDir);
            // 创建目录（如果不存在）
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            // 构建完整的文件路径
            Path filePath = uploadPath.resolve(uniqueFileName);
            // 保存文件
            picture.transferTo(filePath.toFile());
            // 调用业务逻辑处理博客信息
            blog.setPicture(Way+uniqueFileName);
          Integer result = blogService.addBlog(blog);
          if(result!=null){
            return new JsonResult<>(null);
            }else {
              return new JsonResult<>(null, ErrorCode.BLOG_ADD_FAIL);
          }
        } catch (IOException e) {
            e.printStackTrace();
            return new JsonResult<>(null, ErrorCode.BLOG_ADD_FAIL);
        }
    }

    @PostMapping("/addComment")
    public JsonResult<Map> addComment(@RequestBody CommentAdd commentAdd, HttpServletRequest request){
        Integer userId = (Integer) request.getAttribute("id");
        Comment comment = new Comment();
        comment.setCblog(commentAdd.getBlogId());
        comment.setComment(commentAdd.getComment());
        comment.setCuser(userId);
        Integer result = blogService.addComment(comment);
if(result!=null){
    return new JsonResult<>(null);
}else{
    return new JsonResult<>(null, ErrorCode.COMMENT_ADD_FAIL);
}
    }

    @PostMapping("Comments")
    public JsonResult<JSONObject> Comments(@RequestBody Integer blogId){
        JSONObject loginResponse = new JSONObject();
        List<CommentVo> commentList = blogService.getComment(blogId);
        if(commentList!=null){
            loginResponse.put("commentList",commentList);
            return new JsonResult<>(loginResponse);
        }else {
            return new JsonResult<>(null, ErrorCode.COMMENT_SHOW_FAIL);
        }
    }

    @PostMapping("/read")
    public JsonResult<JSONObject> read(@RequestBody Integer blogId){
        JSONObject loginResponse = new JSONObject();
        Integer result = blogService.read(blogId);
if (result!=null){
    loginResponse.put("result",result);
return new JsonResult<>(loginResponse);
}else {
    return new JsonResult<>(null);
}
    }

}

